package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author 石小俊
 * 查询所有员工信息
 * 该页面中涉及到页面的绘制与数据库数据的查询
 */
@WebServlet("/findAll")
public class EmpListServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println(" <!DOCTYPE html> ");
        out.println(" <html lang=\"en\"> ");
        out.println(" <head> ");
        out.println("     <meta charset=\"UTF-8\"> ");
        out.println("     <title>员工列表</title> ");
        out.println(" </head> ");
        out.println(" <body> ");
        out.println(" <h1>员工列表</h1> ");
        out.println(" <a href=\"showAddEmp\">添加员工</a> ");
        out.println(" <hr> ");
        out.println(" <table border=\"1\"> ");
        out.println("     <tr> ");
        out.println("         <th>编号</th> ");
        out.println("         <th>姓名</th> ");
        out.println("         <th>工资</th> ");
        out.println("         <th>操作</th> ");
        out.println("     </tr> ");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            // JDBC操作,查询所有员工信息
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8", "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,name,salary ")
                    .append(" from t_emp")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                out.println("     <tr> ");
                out.println("         <td>" + rs.getInt("id") + "</td> ");
                out.println("         <td>" + rs.getString("name") + "</td> ");
                out.println("         <td>" + rs.getDouble("salary") + "</td> ");
                out.println("         <td> ");
                out.println("             <a href=\"findById?id=" + rs.getInt("id") + "\">修改</a> ");
                out.println("             <a href=\"deleteById?id=" + rs.getInt("id") + "\" onclick=\"confirm('是否确认删除?')\">删除</a> ");
                out.println("         </td> ");
                out.println("     </tr> ");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        out.println(" </table> ");
        out.println(" </body> ");
        out.println(" </html> ");
    }
}
